<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="addTrademark"
      >添加</el-button
    >
    <!-- 表格区域:显示品牌信息  -->
    <el-table
      border
      style="width: 100%; margin: 20px 0"
      :header-cell-style="{ color: 'pink' }"
      :data="records"
    >
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTrademark(row)"
            >修改</el-button
          >
          <!-- 气泡确认框 -->
          <el-popconfirm title="这是一段内容确定删除吗？" icon="el-icon-delete" icon-color='#409EFF' @onConfirm="deleteTrademark(row)">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- 
             -->
    <el-pagination
      align="center"
      @current-change="getTrademarkList"
      @size-change="handleSizeChange"
      :current-page="page"
      :page-sizes="[3, 5, 10, 20]"
      :page-size="limit"
      background
      prev-text="上一页"
      next-text="下一页"
      layout="prev, pager, next,jumper,->,total,sizes"
      :total="total"
    >
    </el-pagination>

    <!-- 添加品牌的对话框 -->
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
      :before-close="close"
      :show-close="false"
    >
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="cur">
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Trademark",
  data() {
    // 自定义校验规则
    const validateTmName = (rule, value, callback) => {
      if (/^[\u4e00-\u9fa5]{2,10}$/.test(value)) {
        callback();
      } else {
        callback(new Error("品牌的名字是汉子2-10个"));
      }
    };
    return {
      total: 0,
      page: 1,
      limit: 5,
      // 存储商品
      records: [],
      // 对话框的显示与隐藏
      dialogFormVisible: false,
      // 收集表单数据的对象
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      // 表单验证的 规则
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "change" },
          // {
          //   min: 2,
          //   max: 20,
          //   message: "长度在 2 到 20 个字符",
          //   trigger: "change",
          // },
          // 自定义校验规则
          { validator: validateTmName, trigger: "change" },
        ],
        logoUrl: [
          { required: true, message: "请选择品牌的LOGO ", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getTrademarkList();
  },
  methods: {
    // 获取商品列表的请求
    async getTrademarkList(pages = 1) {
      this.page = pages;
      let { page, limit } = this;
      let result = await this.$ajax.trademark.reqTrademark(page, limit);
      if (result.code == 200) {
        this.total = result.data.total;
        this.records = result.data.records;
        this.page = result.data.current;
      }
    },
    // 修改一页几个商品的回调
    handleSizeChange(value) {
      this.limit = value;
      this.getTrademarkList();
    },
    // 添加按钮的回调
    addTrademark() {
      this.dialogFormVisible = true;
      //清空之前收集的数据
      this.tmForm = {
        tmName: "",
        logoUrl: "",
      };
    },
    // 图片上传的回调
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 点击确定的回调
    addOrUpdateTrademark() {
      //  点击确定按钮的时候:判断form全部的验证规则全部通过后在发秦秋
      // 获取全部验证结果是否通过,如果有一个没有通过返回的额就是false
      this.$refs.cur.validate(async (success) => {
        if (success) {
          // 关闭对话框
          this.dialogFormVisible = false;

          try {
            // 发请求
            await this.$ajax.trademark.reqAddOrUpdateTrademark(this.tmForm);
            this.$message({
              type: "success",
              message: tmForm.id ? "修改成功" : "添加成功",
            });
            // 获取最新的数据
            this.getTrademarkList(this.tmForm.id ? this.page : 1);
            // 表单重置
            this.$refs.cur.resetFields();
          } catch (error) {
            this.$message({
              type: "error",
              message: this.tmForm.id ? "修改成功" : "添加成功",
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 点击修改按钮
    updateTrademark(row) {
      //  对话框弹出来
      this.dialogFormVisible = true;
      // 进行数据的替换
      this.tmForm = { ...row };
    },
    // 点击取消(对话框)的回调
    cancel() {
      this.dialogFormVisible = false;
      // 获取form重置
      this.$refs.cur.resetFields();
    },
    //
    close() {},
    // 删除
    async deleteTrademark({ id }) {
      // 整理参数
      // 发请求
      try {
        await this.$ajax.trademark.reqDeleteTrademark(id);
        this.$message({
          type: "success",
          message: "删除成功",
        });
        this.getTrademarkList(
          this.records.length > 1 ? this.page : this.page - 1
        );
      } catch (error) {
        this.$message({
          type: "error",
          message: "删除失败",
        });
      }
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>